﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using FileIo = System.IO.File;

using BMCShowView.Business;
using BMCShowView.Portal.Models;
using BMCShowView.Portal.ViewModels;

namespace BMCShowView.Portal.Controllers
{
    public class HomeController : Controller
    {
        public static object HomeLock = new object();

        public void Message()
        {
            Response.ContentType = "text/event-stream";
            Response.CacheControl = "no-cache";
            Response.Flush();
            //while (true)
            {
                lock (HomeLock)
                {
                    Monitor.Wait(HomeLock);
                }
                try
                {
                    Response.Write(string.Format("data: {0}\n\n", "Refresh"));
                    Response.Flush();
                }
                catch (HttpException)
                {
                    // 连接已关闭
                    //break;
                }
            }
        }

        public ActionResult Index()
        {
            var now = DateTime.Now;
            var model = new ArrangeViewModel
            {
                Now = now
            };

            using (var context = new BmcContext())
            {
                model.Announcement = (context.Announcements.OrderByDescending(x => x.CreateTime).FirstOrDefault() ?? new Announcement { Content = "" }).Content;
                model.Remark = (context.Remarks.OrderByDescending(x => x.CreateTime).FirstOrDefault() ?? new Remark()).Content;
            }
            using (var stream = FileIo.Open(Server.MapPath("~/Files/2015-04.xlsx"), FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var list = ArrangeTable.ReadFromStream(stream);
                var today = list[now.Day - 1];
                
                if (now.TimeOfDay >= new TimeSpan(0, 0, 0) && now.TimeOfDay < new TimeSpan(8, 30, 0))
                {
                    var yesterday = now.Day == 1 ? null : list[now.Day - 2];
                    // 前一天的最后一班
                    if (yesterday != null)
                    {
                        model.Runner = yesterday.Last();
                    }
                    else
                    {
                        // 上个月的最后一天，沒数据
                    }
                }
                else if (today.Count == 2)
                {
                    // 两班
                    if (now.TimeOfDay >= new TimeSpan(8, 30, 0) && now.TimeOfDay < new TimeSpan(20, 30, 0))
                    {
                        model.Runner = today[0];
                    }
                    else
                    {
                        model.Runner = today[1];
                    }
                }
                else if (today.Count == 3)
                {
                    // 三班
                    if (now.TimeOfDay >= new TimeSpan(8, 30, 0) && now.TimeOfDay < new TimeSpan(17, 0, 0))
                    {
                        model.Runner = today[0];
                    }
                    else if (now.TimeOfDay >= new TimeSpan(17, 0, 0) && now.TimeOfDay < new TimeSpan(23, 0, 0))
                    {
                        model.Runner = today[1];
                    }
                    else
                    {
                        model.Runner = today[2];
                    }
                }
                else
                {
                    throw new ApplicationException("Invalid data of arrange table");
                }
            }
            using (var stream = FileIo.Open(Server.MapPath("~/Files/值班日志.xlsx"), FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                model.ImportantTasks = DutyLog.ReadFromStream(stream)
                    .Where(x => x.StartTime.Subtract(TimeSpan.FromMinutes(1)) <= now.TimeOfDay && now.TimeOfDay <= x.EndTime.Add(TimeSpan.FromMinutes(1)))
                    .ToArray();
            }
            return View(model);
        }

        public ActionResult ChangeList()
        {
            var result = new ChangeListViewModel();

            result.EventWorkOrders = new List<EventWorkOrder.WorkOrder>();

            var today = DateTime.Now.Date;

            using (var stream = FileIo.Open(Server.MapPath("~/Files/变更页面.xlsx"), FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                result.LatestChanges = LatestChange.ReadFromStream(stream).Where(x => x.Date.Date == today).ToList();
            }

            return View(result);
        }
    }
}